/* eslint-disable */
import axios from 'axios'

// 配置axios基础URL
const API_BASE_URL = 'http://localhost:8081/api'

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000, // 图片上传需要更长的超时时间
  headers: {
    'Content-Type': 'application/json'
  }
})

// 创建文件上传专用的axios实例
const uploadClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 60000, // 文件上传超时时间更长
  headers: {
    'Content-Type': 'multipart/form-data'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  config => {
    console.log('发送图片API请求:', config.method?.toUpperCase(), config.url)
    return config
  },
  error => {
    console.error('图片API请求错误:', error)
    return Promise.reject(error)
  }
)

uploadClient.interceptors.request.use(
  config => {
    console.log('发送文件上传请求:', config.method?.toUpperCase(), config.url)
    return config
  },
  error => {
    console.error('文件上传请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
const responseInterceptor = response => {
  console.log('收到响应:', response.status, response.config.url)
  // 后端返回的数据格式: { success: boolean, message: string, data: any }
  if (response.data && response.data.success) {
    return response.data.data
  } else {
    throw new Error(response.data?.message || '请求失败')
  }
}

const errorInterceptor = error => {
  console.error('响应错误:', error)
  if (error.response) {
    // 服务器返回错误状态码
    const message = error.response.data?.message || `请求失败: ${error.response.status}`
    throw new Error(message)
  } else if (error.request) {
    // 请求发送失败
    throw new Error('网络连接失败，请检查后端服务是否启动')
  } else {
    // 其他错误
    throw new Error(error.message || '未知错误')
  }
}

apiClient.interceptors.response.use(responseInterceptor, errorInterceptor)
uploadClient.interceptors.response.use(responseInterceptor, errorInterceptor)

// 图片API类
class ImageAPI {
  // 上传单个图片
  async upload(file, options = {}) {
    try {
      const {
        articleId = null,
        description = '',
        onProgress = null
      } = options
      
      // 验证文件类型
      if (!this.isValidImageFile(file)) {
        throw new Error('不支持的图片格式，请上传 JPG、PNG、GIF、WebP 格式的图片')
      }
      
      // 验证文件大小（默认最大5MB）
      const maxSize = 5 * 1024 * 1024 // 5MB
      if (file.size > maxSize) {
        throw new Error('图片文件过大，请上传小于5MB的图片')
      }
      
      const formData = new FormData()
      formData.append('file', file)
      if (articleId) formData.append('articleId', articleId)
      if (description) formData.append('description', description)
      
      const config = {}
      if (onProgress) {
        config.onUploadProgress = (progressEvent) => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
          onProgress(percentCompleted)
        }
      }
      
      const result = await uploadClient.post('/images/upload', formData, config)
      return result
    } catch (error) {
      console.error('图片上传失败:', error)
      throw error
    }
  }
  
  // 批量上传图片
  async batchUpload(files, options = {}) {
    try {
      const {
        articleId = null,
        onProgress = null,
        onSingleComplete = null
      } = options
      
      const results = []
      const total = files.length
      
      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        
        try {
          const result = await this.upload(file, {
            articleId,
            onProgress: onProgress ? (percent) => {
              const overallProgress = Math.round(((i + percent / 100) / total) * 100)
              onProgress(overallProgress, i + 1, total)
            } : null
          })
          
          results.push({ success: true, data: result, file })
          
          if (onSingleComplete) {
            onSingleComplete(result, i + 1, total)
          }
        } catch (error) {
          results.push({ success: false, error: error.message, file })
        }
      }
      
      return results
    } catch (error) {
      console.error('批量上传失败:', error)
      throw error
    }
  }
  
  // 通过Base64上传图片（用于粘贴功能）
  async uploadBase64(base64Data, options = {}) {
    try {
      const {
        filename = 'pasted-image.png',
        articleId = null,
        description = '粘贴的图片'
      } = options
      
      // 将Base64转换为Blob
      const blob = this.base64ToBlob(base64Data)
      const file = new File([blob], filename, { type: blob.type })
      
      return await this.upload(file, { articleId, description })
    } catch (error) {
      console.error('Base64图片上传失败:', error)
      throw error
    }
  }
  
  // 获取图片列表
  async getList(params = {}) {
    try {
      const {
        page = 1,
        size = 20,
        articleId = null,
        sortBy = 'createdAt',
        sortOrder = 'desc'
      } = params
      
      const queryParams = {
        page,
        size,
        sortBy,
        sortOrder
      }
      
      if (articleId) queryParams.articleId = articleId
      
      const response = await apiClient.get('/images', { params: queryParams })
      return response
    } catch (error) {
      console.error('获取图片列表失败:', error)
      throw error
    }
  }
  
  // 根据ID获取图片信息
  async getById(id) {
    try {
      const image = await apiClient.get(`/images/${id}`)
      return image
    } catch (error) {
      console.error('获取图片信息失败:', error)
      throw error
    }
  }
  
  // 删除图片
  async delete(id) {
    try {
      await apiClient.delete(`/images/${id}`)
      return true
    } catch (error) {
      console.error('删除图片失败:', error)
      throw error
    }
  }
  
  // 批量删除图片
  async batchDelete(ids) {
    try {
      const result = await apiClient.delete('/images/batch', {
        data: { ids }
      })
      return result
    } catch (error) {
      console.error('批量删除图片失败:', error)
      throw error
    }
  }
  
  // 更新图片信息
  async update(id, updateData) {
    try {
      const updatedImage = await apiClient.put(`/images/${id}`, updateData)
      return updatedImage
    } catch (error) {
      console.error('更新图片信息失败:', error)
      throw error
    }
  }
  
  // 获取图片统计信息
  async getStatistics() {
    try {
      const statistics = await apiClient.get('/images/statistics')
      return statistics
    } catch (error) {
      console.error('获取图片统计信息失败:', error)
      throw error
    }
  }
  
  // 工具方法：验证图片文件类型
  isValidImageFile(file) {
    const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
    return validTypes.includes(file.type)
  }
  
  // 工具方法：Base64转Blob
  base64ToBlob(base64Data) {
    // 移除data:image/xxx;base64,前缀
    const base64 = base64Data.replace(/^data:image\/[a-z]+;base64,/, '')
    
    // 获取图片类型
    const mimeMatch = base64Data.match(/^data:(image\/[a-z]+);base64,/)
    const mimeType = mimeMatch ? mimeMatch[1] : 'image/png'
    
    // 转换为二进制数据
    const byteCharacters = atob(base64)
    const byteNumbers = new Array(byteCharacters.length)
    
    for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i)
    }
    
    const byteArray = new Uint8Array(byteNumbers)
    return new Blob([byteArray], { type: mimeType })
  }
  
  // 工具方法：生成图片预览URL
  getPreviewUrl(imagePath) {
    if (!imagePath) return ''
    
    // 如果已经是完整URL，直接返回
    if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
      return imagePath
    }
    
    // 拼接服务器地址
    return `${API_BASE_URL}/uploads/images/${imagePath}`
  }
  
  // 工具方法：压缩图片
  async compressImage(file, options = {}) {
    return new Promise((resolve) => {
      const {
        maxWidth = 1920,
        maxHeight = 1080,
        quality = 0.8
      } = options
      
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      const img = new Image()
      
      img.onload = () => {
        // 计算压缩后的尺寸
        let { width, height } = img
        
        if (width > maxWidth) {
          height = (height * maxWidth) / width
          width = maxWidth
        }
        
        if (height > maxHeight) {
          width = (width * maxHeight) / height
          height = maxHeight
        }
        
        canvas.width = width
        canvas.height = height
        
        // 绘制压缩后的图片
        ctx.drawImage(img, 0, 0, width, height)
        
        // 转换为Blob
        canvas.toBlob((blob) => {
          const compressedFile = new File([blob], file.name, {
            type: file.type,
            lastModified: Date.now()
          })
          resolve(compressedFile)
        }, file.type, quality)
      }
      
      img.src = URL.createObjectURL(file)
    })
  }
}

// 创建实例并导出
export const imageApi = new ImageAPI()
export default imageApi